<?php

/**
 * ECTouch Open Source Project
 * ============================================================================
 * Copyright (c) 2012-2014 http://ectouch.cn All rights reserved.
 * ----------------------------------------------------------------------------
 * 文件名称：UserModel.php
 * ----------------------------------------------------------------------------
 * 功能描述：ECTouch 用户模型
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.ectouch.cn/docs/license.txt )
 * ----------------------------------------------------------------------------
 */

/* 访问控制 */
defined('IN_ECTOUCH') or die('Deny Access');

class MshopModel extends BaseModel {

    protected $table = 'mshop';
  function getIdByUser_id($user_id) {

     $sql = " SELECT mshop_id FROM " . $this->pre ."mshop WHERE user_id= '$user_id'";
     $data=$this->row($sql);

     return $data['mshop_id'];
    }
    //判断是否存在旅行社，否则不显示ID
    function getIsmshop($mshop_id) {

     $sql = " SELECT mshop_id,user_name FROM " . $this->pre ."users WHERE user_id= '$_SESSION[user_id]'";
     $data=$this->row($sql);

    
     if($data['mshop_id']==$mshop_id)
     {
        return $mshop_id;
     }
     else
     {
         return 0;
     }
    }
    //判断是导游当日选择旅行社是否有效
    function guideIsmshop($user_id) {

     $sql = " SELECT mshop_id,end_mshop_time,utype,mshop_id FROM " . $this->pre ."users WHERE utype=2 and user_id= '$user_id'";
     $data=$this->row($sql);

    
     if($data['end_mshop_time']>time())
     {
        return $data;
     }
     else
     {
         return 0;
     }
    }

    //获取所有旅行社的信息
    function get_list()
    {
     $sql = " SELECT mshop_id,mshop_name FROM " 
            . $this->pre ."mshop  "
            ." order by sort_order desc,mshop_name ";
     return $this->query($sql);
    }
        //获取旅行社信息
  function get_info($mshop_id) {

     $sql = " SELECT *,mshop_name as user_name FROM " 
            . $this->pre ."mshop  "
            ." WHERE mshop_id= '$mshop_id'";
     return $this->row($sql);
    }
  function get_userinfo($user_id) {

     $sql = " SELECT user_id,user_name,email,mobile_phone,mshop_id,utype FROM " . $this->pre ."users WHERE user_id= '$user_id'";

     return $this->row($sql);
    }
  
  //计算旅行社当天所有导游
  function count_child_guide($mshop_id)
  {
    $sql = " SELECT count(*) as num FROM " . $this->pre ."users   ".
        " where mshop_id= '$mshop_id' and utype=2 ";
    $data=$this->row($sql);

     return $data['num'];
  }
  //计算旅行社推荐的所有用户
  function count_child_users($mshop_id)
  {
    $sql = " SELECT count(*) as num FROM " . $this->pre ."users   ".
        " where mshop_id= '$mshop_id' and utype=1 ";
    $data=$this->row($sql);

     return $data['num'];
  }

  //查看店铺及其子店铺的销售情况
  function get_order_sales($mshop_id)
  {
    $sals=array();


    $sals=$this->order_sales_byid($mshop_id);

    $sals['cnum']=$this->count_child_users($mshop_id);
    return $sals;

  }
  //查看店铺的销售情况
  function order_sales_byid($mshop_id)
  {
    //未付款，已完成，退货的订单数和金额
    $sql="select count(*) as num,sum(order_amount) as s_amount from "
          .$this->pre ."order_info WHERE mshop_id= '$mshop_id' and pay_status!=2";
    $fir1=$this->row($sql);

    $sql="select count(*) as num,sum(money_paid) as s_amount from "
          .$this->pre ."order_info WHERE mshop_id= '$mshop_id' and pay_status=2 ";
    $fir2=$this->row($sql);

    $sql="select count(*) as num,sum(order_amount) as s_amount from "
          .$this->pre ."order_info WHERE mshop_id= '$mshop_id' and order_status=4";
    $fir3=$this->row($sql);

    $sals['nopaid_num']=$fir1['num']?$fir1['num']:0;
    $sals['nopaid_amount']=$fir1['s_amount']?$fir1['s_amount']:0;
    $sals['end_num']=$fir2['num']?$fir2['num']:0;
    $sals['end_amount']=$fir2['s_amount']?$fir2['s_amount']:0;
    $sals['return_num']=$fir3['num']?$fir3['num']:0;
    $sals['return_amount']=$fir3['s_amount']?$fir3['s_amount']:0;

    return $sals;
  }


   //佣金的累加或消减
   function deal_profit($order_sn,$mshop_id,$amount,$shipping_fee,$profit=0,$add=0)
   {
		  $k_amount=$amount-$shipping_fee;//计算佣金的营业额
      $result=false;
      $now_time=gmtime();            
		  
		 if($add)
		  { 
		  
		  	 //连续2个同一个订单累加
	      $sql="select order_sn from ".$this->pre."mshop_frozen_profit  where status!=2 and order_sn='$order_sn'";
				$sel_order_sn=$this->row($sql);

       
				if($sel_order_sn['order_sn'])
				{
					return false;
					exit;
				}
				
				
			$sql_infr = " insert into   " . $this->pre ."mshop_frozen_profit(`mshop_id`,`order_sn`,`goods_price`,`frozen_profit`,`ctime`,`status`) values('$mshop_id','$order_sn','$k_amount','$profit','$now_time','1')";
			$insert_fr=$this->query($sql_infr);
			
			if($insert_fr)
			{
				$sql = " update  " . $this->pre ."mshop set sum_amount=sum_amount+$amount,sum_profit=(sum_profit+$profit) WHERE mshop_id= '$mshop_id'";
				$result=$this->query($sql);			
			}

		 }
		 else
		 {			 
			 $sql_pro="update  ".$this->pre ."mshop_frozen_profit  set status=2 where status!=2 and  order_sn='$order_sn'";
             $result_pro=$this->query($sql_pro);
			 
			 if($result_pro)
			 {
			   $sql = " update  " . $this->pre ."mshop set  sum_amount=sum_amount-$amount,sum_profit=(sum_profit-$profit) WHERE mshop_id= '$mshop_id'";
			   $result=$this->query($sql);
			 }

		 }
            
         return $result;
    }
    
    //公众号推广方法链接
    function url_spread($title,$url,$imgurl,$desc)
    {
        //验证导游 是否当日选择旅行社
         $data=$this->guideIsmshop($_SESSION['user_id']);

         if(!$data)//当前选择的旅行社已过期
        {
                show_message('没有选择当日旅行社', '去选择旅行社', url('user/chose_travel_agency'), 'info');
         }

        $status=model('Wechat')->check_is_weixin();
        if(!$status)
        {
            // $mes="分享链接生成失败,必须在微信下进入。";
            return '';
        }

        $signPackage=model('Wechat')->getSignPackage();

        // $title="锦绣天地，欢乐无穷！";
        // $url='http://'.$_SERVER["HTTP_HOST"].url("index/mshop_notice");
        // $imgurl=__URL__."/themes/default/images/wx_open.jpg";
        // $desc="一起来锦绣天地吧！";

        $newsrow['title']=$title;
        $newsrow['url']=$url;
        $newsrow['imgurl']=$imgurl;
        $newsrow['desc']=$desc;

        $html_sg='  <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
        <script>
        wx.config({   
        debug: false,
        appId: \''.$signPackage["appId"]. '\',
        timestamp: '.$signPackage["timestamp"].',
        nonceStr: \''.$signPackage["nonceStr"].'\',
        signature: \''. $signPackage["signature"]. '\',
        jsApiList: [
            \'checkJsApi\',
            \'onMenuShareTimeline\',
            \'onMenuShareAppMessage\',
            \'onMenuShareQQ\',
            \'onMenuShareWeibo\',
            \'hideMenuItems\',
            \'showMenuItems\',
            \'hideAllNonBaseMenuItem\',
            \'showAllNonBaseMenuItem\',
            \'translateVoice\',
            \'startRecord\',
            \'stopRecord\',
            \'onRecordEnd\',
            \'playVoice\',
            \'pauseVoice\',
            \'stopVoice\',
            \'uploadVoice\',
            \'downloadVoice\',
            \'chooseImage\',
            \'previewImage\',
            \'uploadImage\',
            \'downloadImage\',
            \'getNetworkType\',
            \'openLocation\',
            \'getLocation\',
            \'hideOptionMenu\',
            \'showOptionMenu\',
            \'closeWindow\',
            \'scanQRCode\',
            \'chooseWXPay\',
            \'openProductSpecificView\',
            \'addCard\',
            \'chooseCard\',
            \'openCard\'
        ]
      });
      wx.checkJsApi({
          jsApiList: [
            \'getNetworkType\',
            \'previewImage\'
          ],
          success: function (res) {
            alert(JSON.stringify(res));
          }
      });
      wx.ready(function () {
        wx.onMenuShareTimeline({
             title: "'.$newsrow['title'].'",
             link: "'.$newsrow['url'].'",
             imgUrl: "'.$newsrow['imgurl'].'",
             trigger: function (res) {
             },
             success: function (res) {       
             },
             cancel: function (res) {            
             },
             fail: function (res) {
             }
        });
        wx.onMenuShareAppMessage({
            title: "",
            desc: "'.$newsrow['desc'].'",
            link: "'.$newsrow['url'].'",
            imgUrl: "'.$newsrow['imgurl'].'",
            trigger: function (res) {
            },
            success: function (res) {
            },
            cancel: function (res) {
            },
            fail: function (res) {
            }
         });
    });
    </script>';
        return $html_sg;
    } 
//当天第一次登陆
  function login_first()
  {
        //旅行社的优先级高--登录后第一次进入页面
          if($_SESSION['user_id'])
          {
                $user_id=$_SESSION['user_id'];
                $row_u = $this->get_userinfo($user_id);
                $_SESSION['utype']=$row_u['utype'];
               if($row_u['mshop_id'])
               {
                   $_SESSION['user_mshopNo']=$row_u['mshop_id'];
                   $_SESSION['mshopNo']=$row_u['mshop_id'];
                   //记录旅行社名称
                    $row_m =$this->get_info($row_u['mshop_id']);
                    $_SESSION['mshop_name']=$row_m['mshop_name'];
               }
               else//用户没有归属旅行社
               {
                  $_SESSION['mshopNo']='';
                  $_SESSION['user_mshopNo']='XX';
                  $_SESSION['mshop_name']='';
               }
               //判断当日导游归属旅行社是否有效
               if($row_u['utype']==2)
               {
                    //验证导游 是否当日选择旅行社
                   $data=$this->guideIsmshop($user_id);
                   if(!$data)//当前选择的旅行社已过期
                   {
                          show_message('没有选择当日旅行社', '去选择旅行社', url('user/chose_travel_agency'), 'info');
                   }
               }

               $_SESSION['mshop_pname']='';//销毁导游推荐过来的旅行社

          }
  }
  



}
